package redisInit

import (
	"context"
	"fmt"
	"srv/shop"
	"strconv"
)

const GoodsIdStock = "goods_id_num"

func AddGoods(userId, goodsId, goodsNum int, goodsName, goodsState string, goodsPrice float64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"goodsId":    goodsId,
		"goodsNum":   goodsNum,
		"goodsName":  goodsName,
		"goodsState": goodsState,
		"goodsPrice": goodsPrice,
		"userId":     1,
	}).Err()
}
func CheckCart(userId int64, goodsId int64) bool {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.Exists(context.Background(), key).Val() == 1
}

func UpdateCartNum(userId int64, goodsId int64, num int64) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.HSet(context.Background(), key, "num", num).Err()
}

// 添加商品进入redis
func RedisCartAdd(userId uint, num int) {
	key := GoodsIdStock + fmt.Sprintf("%d", userId)
	for i := 0; i < int(num); i++ {
		Rdb.LPush(context.Background(), key, userId)
	}
}
func CartList(userId int64) (cartList []*shop.CartList, err error) {
	key := fmt.Sprintf("%d:*", userId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		all := Rdb.HGetAll(context.Background(), s).Val()
		goodsId, _ := strconv.Atoi(all["goodsId"])
		goodsName, _ := all["goodsName"]
		goodsNum, _ := strconv.Atoi(all["goodsNum"])
		goodsPrice, _ := strconv.ParseFloat(all["goodsPrice"], 64)
		cartList = append(cartList, &shop.CartList{
			GoodsId:    int64(goodsId),
			GoodsNum:   int64(goodsNum),
			GoodsName:  goodsName,
			GoodsPrice: float32(goodsPrice),
		})
	}
	return
}

//func CartList(userId int64) (cartList []*srv.CartList, err error) {
//	key := fmt.Sprintf("%d:*", userId)
//	keys := RDB.Keys(context.Background(), key).Val()
//	for _, i2 := range keys {
//		all := RDB.HGetAll(context.Background(), i2).Val()
//		goodsId, _ := strconv.Atoi(all["goodsId"])
//		num, _ := strconv.Atoi(all["num"])
//		goodsPrice, _ := strconv.ParseFloat(all["amount"], 64)
//		cartList = append(cartList, &srv.CartList{
//			GoodsId:    int64(goodsId),
//			Num:        int64(num),
//			GoodsTitle: all["goodsTitle"],
//			GoodsPrice: float32(goodsPrice),
//			GoodsCover: all["goodsCover"],
//		})
//	}
//	return
//}
